package com.offcn.order.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Configuration
@EnableResourceServer  // 开启资源服务器
// 激活在方法前的权限校验 @PreAuthorize
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    // 引入公钥
    private static final String PUBLIC_KEY = "public.key";

    /**
     * 读取公钥的数据
     */
    private String getPublicKey(){
        ClassPathResource resource = new ClassPathResource(PUBLIC_KEY);
        try (
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        ){
            String publicKey = bufferedReader.readLine();
            return publicKey;
        } catch(IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * JwtTokenStore
     */
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter){
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    /**
     * JwtAccessTokenConverter
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setVerifierKey(getPublicKey());
        return tokenConverter;
    }

    /**
     * http的安全配置  设定拦截规格和放行规则
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //"/cart1/addItemToCartList","/cart1/findCartList"
                .antMatchers().permitAll()  //放行
                .anyRequest()
                .authenticated(); // 令牌校验不通过或没有令牌 ，所有路径都被拦截
    }
}
